package com.mes_for_xxxxxx.interceptor;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mes_for_xxxxxx.context.BaseContext;
import com.mes_for_xxxxxx.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author LJK
 * @description
 * @date 2024/9/15
 */
@Slf4j
@Component
public class JwtUserInterceptor implements HandlerInterceptor {

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;

        }

        try {
            //1、从请求体中一个名为token的参数获取令牌
//            ObjectMapper mapper=new ObjectMapper();
//            JsonNode rootNode = mapper.readTree(request.getInputStream());
//            JsonNode tokenNode = rootNode.path("token");
//            String token = tokenNode.asText();
//
//            //2、校验令牌
//            log.info("jwt校验:{}", token);
//            Claims claims = JwtUtil.parseJWT("ezLogin", token);
//            Long userId = Long.valueOf(claims.get("employee_id").toString());
//            log.info("当前用户id：{}", userId);
//            BaseContext.setCurrentId(userId);

            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }
}
